package gs.android.calcfeud;

import java.util.Calendar;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameView extends SurfaceView implements Runnable {
	private static final int FPS = 1000 / 10;
	public static final int BOTTOM = 3;
	public static float GAME_MULTIPLIER = 0.5f;
	public static int GAME_WIDTH = (int)(GamePersistor.SCREEN_WIDTH / GAME_MULTIPLIER);
	
	private GamePersistor persistor;
	private SurfaceHolder holder;
	private Thread t = null;
	
	public boolean running = false;
	private long time;
	
	public GameView(Context context) {
		super(context);
		persistor = (GamePersistor) context;
	}
	
	public GameView(Context context, AttributeSet attrs) {
		super(context, attrs);
		try {
			persistor = (GamePersistor) context;
		} catch (Exception e) { }
	}
	
	public GameView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		persistor = (GamePersistor) context;
	}
	
	@Override
	protected void onFinishInflate() {
		holder = getHolder();
		time = Calendar.getInstance().getTimeInMillis();
	}

	@Override
	public void run() {
		while (running) {
			if (!holder.getSurface().isValid()) {
				continue;
			}
			
			// lock canvas to draw
			Canvas c = holder.lockCanvas();
			
			long timeEnd = Calendar.getInstance().getTimeInMillis();
			int elapsed = (int)(timeEnd - time);
			if (elapsed < FPS) {
				try {
					Thread.sleep(FPS - elapsed);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			timeEnd = Calendar.getInstance().getTimeInMillis();
			elapsed = (int)(timeEnd - time);
			time = timeEnd;
			
			// draw objects
			Field[] fields = persistor.getModel().getFields();
			if (fields != null) {
				for (int i = 0; i < fields.length; i++) {
					if (fields[i] != null) {
						fields[i].onDraw(c, 0);
						//Log.d("CalcFeud", "" + i);
					}
				}
			}
			
			// draw roll button
			Button roll = persistor.getModel().getButton();
			roll.onDraw(c, 0);
			
			// draw dice
			Dice dice = persistor.getModel().getDice();
			dice.onDraw(c, 0);
			
			// draw player home
			Player home = persistor.getModel().getHome();
			home.onDraw(c, 0);
			
			// draw player away
			Player away = persistor.getModel().getAway();
			away.onDraw(c, 0);
			
			// unlock and post the drawn canvas
			holder.unlockCanvasAndPost(c);
		}
	}
	
	public void onPause() {
		running = false;
		while (true) {
			try {
				t.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			break;
		}
	}
	
	public void onResume() {
		running = true;
		t = new Thread(this);
		t.start();
		time = Calendar.getInstance().getTimeInMillis();
	}
}